'use strict';
import React from 'react';
import DescTextarea from './descTextarea';

export  class CompletionQuestion extends React.Component{
	_getSpace(props){
		var title = props.question.title;
		return  title.match(/\(__\d__\)/g);
	}

	_handleChange(e){
		this.state.answer[parseInt(e.target.name)] = e.target.value;
	}
	_handleDesc(desc){
		this.state.desc = desc;
		if(this.props._answer){
			this.props._answer({desc:desc});
		}
	}
	getAnswer(){
		if(_.compact(this.state.answer).length != this.state.spaces.length){
			return false;
		}else{
			 return {
			 	answer:this.state.answer,
			 	desc : this.state.desc
			 }
		}
	}
	shouldComponentUpdate(nextProps,nextState){
		console.log('shouldComponentUpdate...........');
		console.log(nextProps.question.title);
		console.log(this.props.question.title);
		console.log(nextState.answer);
		console.log(this.state.answer);
		if(nextProps.question.title != this.props.question.title){
			console.log('ssssssssssssssssssssssssss');
			this._handleInit(nextProps);
			return true;
		}else{
			return false;
		}
	}
	componentDidUpdate(nexProps,nextState){
		console.log('componentDidUpdate..............');
		console.log(this.state);
		if(!this.props.curValue || !this.props.curValue.answer){
			this.setState({answer : Array(this.state.spaces.length)});
		}else{
			this.setState({answer : this.props.curValue.answer});
		}
		//this.render();
	}
	componentWillReceiveProps(){
		console.log('componentWillReceiveProps ----------------------------')
	}
	componentDidMount(){
		console.log('componentDidMount/..............');
		//this._handleInit();
	}
	constructor(props){
		super(props);
		console.log('constructor...........');
		this.state = {desc:''};
		this._handleInit(this.props);
	}
	_handleInit(props){
		this.state.spaces = this._getSpace(props);
		console.log(this.props);
		if(!props.curValue || !props.curValue.answer){
			console.log('--------------------------------')
			this.state.answer = Array(this.state.spaces.length);
		}else{
			this.state.answer = props.curValue.answer;
		}
	}
	render(){
		console.log('CompletionQuestion render ...........');
		console.log(this.props.answer);
		var self = this;
		var res = _.map(this.state.spaces,function(s,ind){
			return <div className='input-group' key={'comp_'+ind}>
					  <span className='input-group-addon' id='basic-addon1'>{s}:</span>
					  <input type='text' className='form-control' 
					  name={ind}
					  defaultValue={self.state.answer[ind]} 
					  onChange={self._handleChange.bind(self)} />
					</div>;
		});
		return (
			<div className='panel panel-info'>
				<div className='panel-heading'>
					{this.props.question.title}
				</div>
				<div className='panel-body'>
					{res}
				</div>
				<DescTextarea _answer={this._handleDesc.bind(this)} curValue={this.props.curValue.desc}/>
			</div>
		);
	}
}
CompletionQuestion.defaultProps = {
	curValue:{
		answer:[],
		desc:''
	}
};